- Notifications
You must be signed in to change notification settings - Fork 5.8k
/
Copy path433. Minimum Genetic Mutation.go
124 lines (117 loc) · 2.2 KB
/
433. Minimum Genetic Mutation.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package leetcode
// 解法一 BFS
funcminMutation(startstring, endstring, bank []string) int {
wordMap, que, depth:=getWordMap(bank, start), []string{start}, 0
forlen(que) >0 {
depth++
qlen:=len(que)
fori:=0; i<qlen; i++ {
word:=que[0]
que=que[1:]
candidates:=getCandidates433(word)
for_, candidate:=rangecandidates {
if_, ok:=wordMap[candidate]; ok {
ifcandidate==end {
returndepth
}
delete(wordMap, candidate)
que=append(que, candidate)
}
}
}
}
return-1
}
funcgetWordMap(wordList []string, beginWordstring) map[string]int {
wordMap:=make(map[string]int)
fori, word:=rangewordList {
if_, ok:=wordMap[word]; !ok {
ifword!=beginWord {
wordMap[word] =i
}
}
}
returnwordMap
}
funcgetCandidates433(wordstring) []string {
varres []string
fori:=0; i<26; i++ {
forj:=0; j<len(word); j++ {
ifword[j] !=byte(int('A')+i) {
res=append(res, word[:j]+string(rune(int('A')+i))+word[j+1:])
}
}
}
returnres
}
// 解法二 DFS
funcminMutation1(startstring, endstring, bank []string) int {
endGene:=convert(end)
startGene:=convert(start)
m:=make(map[uint32]struct{})
for_, gene:=rangebank {
m[convert(gene)] =struct{}{}
}
if_, ok:=m[endGene]; !ok {
return-1
}
ifcheck(startGene^endGene) {
return1
}
delete(m, startGene)
step:=make(map[uint32]int)
step[endGene] =0
returndfsMutation(startGene, m, step)
}
funcdfsMutation(startuint32, mmap[uint32]struct{}, stepmap[uint32]int) int {
ifv, ok:=step[start]; ok {
returnv
}
c:=-1
step[start] =c
fork:=rangem {
ifcheck(k^start) {
next:=dfsMutation(k, m, step)
ifnext!=-1 {
ifc==-1||c>next {
c=next+1
}
}
}
}
step[start] =c
returnc
}
funccheck(valuint32) bool {
ifval==0 {
returnfalse
}
ifval&(val-1) ==0 {
returntrue
}
forval>0 {
ifval==3 {
returntrue
}
ifval&3!=0 {
returnfalse
}
val>>=2
}
returnfalse
}
funcconvert(genestring) uint32 {
varvuint32
for_, c:=rangegene {
v<<=2
switchc {
case'C':
v|=1
case'G':
v|=2
case'T':
v|=3
}
}
returnv
}